package com.spl.seriallibrary.locker.rocktech;

import android.content.Context;

import com.spl.seriallibrary.locker.IHandle;
import com.spl.seriallibrary.util.Constant;
import com.spl.seriallibrary.util.SerialPortTools;



public class RocktechHandle implements IHandle {

    @Override
    public Object checkData(byte[] LISHIZHI, byte[] buffer) {
        if (buffer.length == 1 && buffer[0] == 9) {
            return Constant.CheckResultTYPE.OVERTIME;
        }
        if ((LISHIZHI.length > 2) && ((LISHIZHI[0] != -86) || (LISHIZHI[1] != 0x55))) {
            return Constant.CheckResultTYPE.DATA_HEADE_RERROR;
        }
        if (LISHIZHI.length > 3) {
            if (LISHIZHI[2] == (LISHIZHI.length - 4)) {
                byte crc8 = SerialPortTools.calcCrc8(LISHIZHI, 0, LISHIZHI.length - 1);
                if (LISHIZHI[LISHIZHI.length - 1] == crc8) {
                    return Constant.CheckResultTYPE.RESULT_OK;
                }
            } else {
                if (LISHIZHI.length >= 154) {
                    return Constant.CheckResultTYPE._485_ENOUGH_LENGTH;
                }
            }
        } else {
            return Constant.CheckResultTYPE.NOT_ENOUGH_LENGTH;
        }
        return -1;
    }

    @Override
    public boolean stateQuerySingleLock(byte[] bt, String boxId, Context context) {
        if (bt.length == 1) {
            return false;
        }
        int num = SerialPortTools.calculateLock(boxId) - 1;
        boolean b = true;
        if ("Z00".equals(boxId)) {
            return false;
        }
        switch (num / 8) {
            case 0:
                return (((bt[5] >> (num % 8)) & 1) == 0) ? (!b) : b;
            case 1:
                return (((bt[6] >> (num % 8)) & 1) == 0) ? (!b) : b;
            case 2:
                return (((bt[7] >> (num % 8)) & 1) == 0) ? (!b) : b;
            case 3:
                return (((bt[8] >> (num % 8)) & 1) == 0) ? (!b) : b;
            case 4:
                return (((bt[9] >> (num % 8)) & 1) == 0) ? (!b) : b;
            case 5:
                return (((bt[10] >> (num % 8)) & 1) == 0) ? (!b) : b;
            default:
                return false;
        }
    }

    @Override
    public boolean stateOpenSingleLock(byte[] LISHIZHI, String boxId, Context context) {
        return stateQuerySingleLock(LISHIZHI, boxId, context);
    }

}
